package com.wing.sell.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.sell.model.entity.ContactInfo;
import com.wing.sell.model.entity.CustomersInfo;
import com.wing.sell.model.request.ContactInfoForm;
import com.wing.sell.model.response.ContactInfoVO;
import com.wing.sell.service.ContactInfoService;
import com.wing.sell.service.CustomersInfoService;
import com.wing.user.feign.UserClient;
import com.wing.user.model.request.User;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author
 */
@Validated
@Api(value = "Admin-客户联系人信息管理", tags = "#/sell/contactInfo")
@RestController("contactInfoController")
@RequestMapping("sell/admin/contactInfo")
@RequiredArgsConstructor
public class ContactInfoController {

    private final ContactInfoService contactInfoService;

    @Resource
    CustomersInfoService customersInfoService;

    @Resource
    UserClient userClient;


    @Resource
    private PasswordEncoder passwordEncoder;

    @ApiOperation(value = "查询所有客户联系人信息", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            , @ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            , @ApiImplicitParam(name = "sort", value = "排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            , @ApiImplicitParam(name = "order", value = "排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<ContactInfoVO> list(
            @RequestParam(defaultValue = "1") Integer page
            , @RequestParam(defaultValue = "10") Integer limit
            , @RequestParam(defaultValue = "create_time") String sort
            , @RequestParam(defaultValue = "asc") String order
            , String customerName
            , Long selCustomerId
            , Long id
    ) {

        Page<ContactInfoVO> pg = new Page<>(page, limit);
        Map<String, Object> params = new HashMap<>();

        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            //params.put("sort", StrUtil.toUnderlineCase(sort));
            params.put("sort", sort);
            params.put("order", order);
        }
        if (StringUtils.isNotEmpty(customerName)) {
            params.put("name", customerName);
        }
        params.put("selCustomerId", selCustomerId);
        params.put("id", id);

        IPage<ContactInfoVO> list = contactInfoService.pageList4app(pg, params);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }


    @ApiOperation(value = "添加客户联系人信息", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@Validated(ContactInfoForm.Add.class) ContactInfoForm contactInfoForm) {
        if (contactInfoService.add(contactInfoForm) > 0) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }


    @ApiOperation(value = "修改客户联系人信息", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@Validated(ContactInfoForm.Update.class) ContactInfoForm contactInfoForm) {
        ContactInfo contactInfo = contactInfoService.getById(contactInfoForm.getId());
        if (contactInfo == null) {
            return JsonResult.fail("修改失败！");
        }

        //所属客户信息
        CustomersInfo customersInfo = customersInfoService.getById(contactInfoForm.getSelCustomerId());

        if(customersInfo.getCustomerType().getValue() == 3){
            //修改用户
            User user = new User();
            user.setNickname(contactInfoForm.getName());
            user.setOldPhone(contactInfo.getTelephone());
            user.setUsername(contactInfoForm.getTelephone());
            user.setPhone(contactInfoForm.getTelephone());
            if(contactInfoForm.getPassword() != null){
                if (!contactInfoForm.getPassword().equals( contactInfo.getPassword())){
                    user.setPassword(passwordEncoder.encode(DigestUtil.md5Hex(contactInfoForm.getPassword())));
                }
            }
            userClient.updateThirdUser(user);
        }
        if(contactInfoForm.getPassword() != null){
            if (!contactInfoForm.getPassword().equals( contactInfo.getPassword())){
                contactInfoForm.setPassword(passwordEncoder.encode(DigestUtil.md5Hex(contactInfoForm.getPassword())));
            }
        }
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(ContactInfo.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(contactInfoForm, contactInfo, copyOptions);

        if (contactInfoService.updateById(contactInfo)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }


    @ApiOperation(value = "删除客户联系人信息", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "contactInfoId", value = "客户联系人信息id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}")
    public JsonResult delete(@PathVariable("id") Long contactInfoId) {
        ContactInfo contactInfo = contactInfoService.getById(contactInfoId);
        //所属客户信息
        CustomersInfo customersInfo = customersInfoService.getById(contactInfo.getSelCustomerId());
        if(customersInfo.getCustomerType().getValue() == 3){
            //删除用户
            userClient.delThirdUser(contactInfo.getTelephone());
        }
        if (contactInfoService.removeById(contactInfoId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }
}
